<?php

namespace App\Api\Controllers;

use App\Api\Requests\SearchRequest;
use App\Api\TransFormers\CouponTransformer;
use App\Api\TransFormers\SearchTransformer;
use App\Models\Coupon;
use App\Models\Keyword;
use App\Models\SearchLog;
use Carbon\Carbon;
use Illuminate\Pagination\LengthAwarePaginator;

class SearchController extends BaseController
{


    /**
     * 搜索接口
     *
     * @param SearchRequest $request
     * @return \Dingo\Api\Http\Response
     */
    public function search(SearchRequest $request)
    {
        $lists = Coupon::search($request->get('search'))
            ->where('status', 1)->where('verify', 2)->where('count',1)->get();

        # 添加搜索记录
        $ins = new SearchLog();
        $ins->keyword = $request->get('search');
        $ins->ip = get_client_ip();
        $ins->save();

        $lists = $this->getNearLists($lists, $request->get('longitude'),$request->get('latitude'));
        $pageNow = $request->get('page', 1);
        $pageSize = 10;
        $lists = new LengthAwarePaginator($lists->forPage($pageNow, $pageSize), $lists->count(), $pageSize);

        return $this->response->paginator($lists, new CouponTransformer());
    }

    public function getNearLists($lists,$lng, $lat, $where = [] ,$distance = 50000)
    {
        $offsets = get_lng_and_lat_deviation($lng, $lat, $distance);

        $res = $lists->filter(function ($item, $key) use ($offsets, $lng, $lat){
            if($item->start > Carbon::now() || $item->end < Carbon::now())
                return false;
            $filterStatus = false;
            if(\App::environment('local','staging'))
                $filterStatus = true;
            if(($item->longitude >= $offsets['lng'][0] && $item->longitude <= $offsets['lng'][1]) && ($item->latitude >= $offsets['lat'][0] && $item->latitude <= $offsets['lat'][1]))
                $filterStatus = true;

            if($filterStatus){
                $tmpNum = get_lng_and_lat_distance($item->latitude, $item->longitude, $lat, $lng);
                $item->distanceNum = $tmpNum;
                $item->distance = get_distance_text($tmpNum);
            }
            return $filterStatus;
        });

        if (!$res->count())
            return collect();
        return $res->sortBy('distanceNum');
    }

}